import axios from "axios";
import qs from "qs"
import {Toast} from "antd-mobile"
import {getUserInfo,actions} from "../store/modules/login"
import store from "../store"

//请求拦截
axios.interceptors.request.use(req=>{
    if(req.url!="/api/login"&&req.url!=="/api/register"){
        req.headers.authorization=getUserInfo(store.getState()).token;
        console.log(store.getState());
    }
    return req
})

//响应拦截
axios.interceptors.response.use(res=>{
    //打印结果
    console.group("本次请求地址："+res.config.url);
    console.log(res);
    console.groupEnd();
    
    //统一处理失败
    if(res.data.code!=200){
        Toast.show({
            content: res.data.msg,
        })
    }

    //统一处理掉线
    if(res.data.msg=="登录已过期或访问权限受限"){
        // sessionStorage.removeItem("userInfo");
        store.dispatch(actions.changeUserInfo({}))
        window.open("/login","_self");
    }

    return res
})


//封装get
export const get = (url,params={})=>{
    return axios({
        url,
        method:"get",
        params
    })
}

//封装post
export const post = (url,data={},isFile=false)=>{
    let params = null;
    if(isFile){
        //有文件
        params = new FormData();
        for(let key in data){
            params.append(key,data[key])
        }
    }
    else{
        //没有文件
        params=qs.stringify(data);
    }
    return axios({
        url,
        method:"post",
        data:params
    })
}